<template>
    <div class="upload-file" style="display:flex">
        <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList"
            :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
            :show-file-list="false" :headers="headers" class="upload-file-uploader" ref="fileUpload" :data="uploadData" >
            <!-- 上传按钮 -->
            　<el-button class="upload_btn"   type="primary" icon="el-icon-upload">上传文件</el-button>
            <!-- 上传提示 -->
            <!-- <span style="color: red">（温馨提示：单个文件不超过5M）</span> -->
            <!-- <span class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
            </span> -->
        </el-upload>

    
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
    dicts: ['WJLX'], // 门类树添加---原文类型
    name: "FileUpload",
    props: {
        uploadData: [String, Object, Array], //参数
        // 值
        value: [String, Object, Array],
        // 大小限制(MB)
        fileSize: {
            type: Number,
            default: 25,
        },
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: {
            type: Array,
            // default: () => ["doc","docx","xls","xlsx", "ppt", "txt", "pdf","mp4","mp3","png","jpg","jpeg"],
            default: () => [],
        },
        // 是否显示提示
        isShowTip: {
            type: Boolean,
            default: true
        },
        uploadFileUrl: [String], //上传文件服务器地址
        istype: [String], //如果是文件接收传过来的“1” ，判断选择文件类型
       
    },

    data() {
        return {
            number: 0,
            // uploadFileUrl: process.env.VUE_APP_BASE_API + "/archive/lxjs/upload", // 上传文件服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            fileList: [],
            uploadList: [],
            list: []
        };
    },
    watch: {
        value: {
            handler(val) {
                if (val) {
                    //     let temp = 1;
                    //     // 首先将值转为数组
                    //     const list = Array.isArray(val) ? val : this.value.split(',');
                    //     // 然后将数组转为对象数组
                    //     this.fileList = list.map(item => {
                    //         if (typeof item === "string") {
                    //             item = { name: item, url: item };
                    //         }
                    //         item.uid = item.uid || new Date().getTime() + temp++;
                    //         return item;
                    //     });
                    this.fileList = val;
                } else {
                    this.fileList = [];
                    // return [];
                }
            },
            deep: true,
            immediate: true
        }
    },
    computed: {
        // 是否显示提示
        showTip() {
            return this.isShowTip && (this.fileType || this.fileSize);
        },
    },
    methods: {
        // 上传前校检格式和大小
        handleBeforeUpload(file) {

            if (this.istype == "1") {
                if (this.uploadData == undefined) {
                    this.$message.warning(`请选择文件类型`);
                    return false
                }
            }
            // 校检文件类型
            if (this.fileType.length > 0) {
                const fileName = file.name.split('.');
                const fileExt = fileName[fileName.length - 1];
                const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
                if (!isTypeOk) {
                    this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
                    return false;
                }
            }
            // 校检文件大小
            // if (this.fileSize) {
            //     const isLt = file.size / 1024 / 1024 < this.fileSize;
            //     if (!isLt) {
            //         this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            //         return false;
            //     }
            // }
            this.$modal.loading("正在上传文件，请稍候...");
            this.list = [];
            this.number++;
            return true;
        },
        // 文件个数超出
        handleExceed() {
            this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        },
        // 上传失败
        handleUploadError(err) {
            this.$modal.msgError("上传文件失败，请重试");
            this.$modal.closeLoading()
        },
        // 上传成功回调
        handleUploadSuccess(res, file, fileList) {
            // console.log('res: ', res)
            // console.log('file: ', file)
            // console.log('fileList: ', fileList, this.fileList)
            this.list.push(res)

            if (res.code == 500) {
                this.$modal.msgError(res.msg);
            }


            // if (fileList.every(item => item.status == 'success')) {

            //     fileList.map(item => {
            //         /** 这时只需要push进带有response的数据就好 */
            //         if (item.response) {
            //             if (item.response.code === 200) {
            //                 if (this.istype == "1") {
            //                     //文件收集上传
            //                     this.fileList.push(item.response.data.docInfo)
            //                 } else {
            //                     //开放鉴定添加上传文件
            //                     this.fileList.push({
            //                         FILE_NAME: item.response.data.fileName,
            //                         FILE_SIZE: item.response.data.fileSize,
            //                         ID: item.response.data.id,
            //                         PATH: item.response.data.path,
            //                         REAL_FILE_NAME: item.response.data.realFileName,
            //                         RENWUID: item.response.data.renwuid,
            //                     })
            //                 }

            //             } else {
            //                 // console.log(item,"++++++++++++++++++++++++++++文件不支持提示")
            //                 // this.$modal.msgError(item.response.msg);

            //             }

            //         }
            //     })
            // }

            var dataArr = [];
            if (this.list.length == this.number) {  //判断上传数据是不是最后一条
                dataArr = this.list;
                this.number = 0;
                var data = dataArr.filter(item => { return item.code == "200" })
                data.map(item => {
                    /** 这时只需要push进带有response的数据就好 */
                    if (item.code === 200) {
                        if (this.istype == "1") {
                            //文件收集上传
                            this.fileList.push(item.data.docInfo)
                        } else {
                            //开放鉴定添加上传文件
                            this.fileList.push({
                                FILE_NAME: item.data.fileName,
                                FILE_SIZE: item.data.fileSize,
                                ID: item.data.id,
                                PATH: item.data.path,
                                REAL_FILE_NAME: item.data.realFileName,
                                RENWUID: item.data.renwuid,
                                MJ:item.data.mj
                            })
                        }

                    } else {
                        // console.log(item,"++++++++++++++++++++++++++++文件不支持提示")
                        // this.$modal.msgError(item.response.msg);

                    }


                })
                this.$emit("handleUploadSuccess", this.fileList, data);
                this.$modal.closeLoading();
            }


            // this.uploadList = [];
            // this.uploadList.push(res.data.docInfo);
            // if (res.code === 200) {
            //     if (this.istype == "1") {
            //     for (var j in this.dict.type.WJLX) {
            //         if (res.data.docInfo.TYPE == this.dict.type.WJLX[j].value) {
            //             res.data.docInfo.TYPE = this.dict.type.WJLX[j].label
            //         }
            //     }

            //     this.uploadList.push(res.data.docInfo);
            // }else{
            //     this.uploadList.push(res.data);
            // }
            // this.uploadedSuccessfully();
            // } else {
            //     this.number--;
            //     this.$modal.closeLoading();
            //     this.$modal.msgError(res.msg);
            //     this.$refs.fileUpload.handleRemove(file);
            //     this.uploadedSuccessfully();
            // }

        },

        // 上传结束处理
        uploadedSuccessfully() {
            console.log("+++++++++++++liuhaorng++++++++")
            // if (this.number > 0 && this.uploadList.length === this.number) {
            this.fileList = this.fileList.concat(this.uploadList);
            this.uploadList = [];
            this.number = 0;
            this.$emit("handleUploadSuccess", this.fileList);
            this.$modal.closeLoading();

            // }
        },

    }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
    margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
}

.upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
}

.ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
}

button {
    margin-left: 20px;
}
</style>
